public class Solution463 {
    public int islandPerimeter(int[][] grid) {
        int m=grid.length,n=grid[0].length;
        int ans=0;
        int[] dx={1,0,-1,0};
        int[] dy={0,1,0,-1};
        for (int i=0;i<m;i++){
            for (int j=0;j<n;j++){
                if (grid[i][j]==1){
                    for (int k=0;k<4;k++){
                        int x=i+dx[k];
                        int y=j+dy[k];
                        if (!valid(x,y,m,n) || grid[x][y]==0){
                            ans++;
                        }
                    }
                }
            }
        }
        return ans;
    }

    boolean valid(int x,int y,int m,int n){
        return x>=0 && x<m && y>=0 && y<n;
    }

    public static void main(String[] args) {
        System.out.println(new Solution463().islandPerimeter(new int[][]{{0,1,0,0},{1,1,1,0},{0,1,0,0},{1,1,0,0}}));
    }
}
